/*
 * AvatarAbiltyResource.cpp
 *
 *  Created on: 2013. 11. 8.
 *      Author: mega@gamevil.com
 */

#include <Database/Static.h>

#include "../NUtil/Pool.h"
#include "AvatarAbiltyResource.h"


namespace ProjectZ { namespace NResource {

AvatarAblityResource::AvatarAblityResource()
{

}

AvatarAblityResource::~AvatarAblityResource()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), ProjectZ::NUtil::del_second_ptr<AVATARABLITYTREE::value_type>);
}

void
AvatarAblityResource::Clear()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), ProjectZ::NUtil::del_second_ptr<AVATARABLITYTREE::value_type>);
	clsFlyTree.clear();
}

bool
AvatarAblityResource::LoadResource()
{
	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::SELECT);
	clsAuto->MakeQuery("select * from resource_avatar_ablity");

	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
		return false;

	if( clsAuto->GetErrorIdx() != 0 )
		return false;

	if (0 == clsAuto->ResultRowCount())
		return false;

	Clear();

	while( clsAuto->Next() )
	{
		::Toolkit::Str<3> NATIONAL_CODE;
		Flyweight * pFly = new Flyweight;

		clsAuto->GetRecord() >> NATIONAL_CODE >> pFly->_LEVEL >> pFly->_ADD_MIN >> pFly->_ADD_MAX >> pFly->_NEED_ZEN;

		if (0 != Config::Instance().GetResourceDatabase()._strNational.compare(NATIONAL_CODE.c_str()))
		{
			DEBUGLOG("%s:%d NATIONAL_CODE ERROR!!! Config National Code [%s] , Resource National Code [%s]",
					__FILE__, __LINE__,
					Config::Instance().GetResourceDatabase()._strNational.c_str(),
					NATIONAL_CODE.c_str());
			return false;
		}

		clsFlyTree[pFly->_LEVEL] = pFly;
	}

	return true;
}

AvatarAblityResource::Flyweight *
AvatarAblityResource::GetFly(int level)
{
	int nLevel = 1;

	if (level >= 10) {
		nLevel = (level / 10) * 10;
	}

	auto iter = clsFlyTree.find(nLevel);
	if (iter == clsFlyTree.end())
		return NULL;

	return iter->second;
}

} /*namespace NResource*/ } /*namespace ProjectZ*/

